package thread.volatile_test;

import java.util.Scanner;

/**
 * @author yuisama
 * @date 2022/06/23 21:29
 **/
public class Volatile {
    private static class Counter {
        volatile int flag = 0;
    }
    public static void main(String[] args) {
        Counter counter = new Counter();
        Thread t1 = new Thread(() -> {
            // volatile变量每次都读写主内存
//            while (counter.flag == 0) {
//                // 一直循环..
//            };
            while (true) {
                synchronized (counter) {
                    if (counter.flag == 0) {
                        continue;
                    }else {
                        break;
                    }
                }
            }
            System.out.println(counter.flag + "退出循环");
        });
        t1.start();
        Thread t2 = new Thread(() -> {
            Scanner scanner = new Scanner(System.in);
            System.out.println("请改变flag的值");
            counter.flag = scanner.nextInt();
        });
        t2.start();
    }
}